package com.ybw.captcha.service.impl;

import com.alibaba.fastjson2.JSON;
import com.tencentcloudapi.captcha.v20190722.CaptchaClient;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultRequest;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultResponse;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.ybw.captcha.config.CaptchaProperties;
import com.ybw.captcha.constant.CaptchaCodeConstant;
import com.ybw.captcha.service.UserService;
import com.ybw.captcha.utils.IPUtils;
import com.ybw.captcha.vo.req.SendSmsReqVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private CaptchaClient client;
    @Resource
    private CaptchaProperties captchaProperties;
    @Resource
    private IPUtils ipUtils;


    @Override
    public Boolean checkCaptcha(SendSmsReqVO sendSmsReqVO) {
        // 实例化一个请求对象,每个接口都会对应一个request对象
        DescribeCaptchaResultRequest req = new DescribeCaptchaResultRequest();
        req.setCaptchaAppId(captchaProperties.getCaptchaAppId());
        req.setAppSecretKey(captchaProperties.getAppSecretKey());
        req.setCaptchaType(captchaProperties.getCaptchaType());
        req.setRandstr(sendSmsReqVO.getRandstr());
        req.setUserIp(ipUtils.getIpAddr());
        req.setTicket(sendSmsReqVO.getTicket());
        try {
            // 返回的resp是一个DescribeCaptchaResultResponse的实例，与请求对象对应
            DescribeCaptchaResultResponse resp = client.DescribeCaptchaResult(req);
            log.info("UserServiceImpl checkCaptcha resp:{}", JSON.toJSONString(resp));
            if (CaptchaCodeConstant.OK.equals(resp.getCaptchaCode())) {
                return true;
            }
            return false;
        } catch (TencentCloudSDKException e) {
            log.error("UserServiceImpl checkCaptcha error:", e);
            return false;
        }
    }
}
